import express from 'express';
import router from './routes/index.js';
import users from './routes/users.js';
import orders from './routes/orders.js';
import session from 'express-session';
import cookieParser from 'cookie-parser';

const app = express();
app.use(session({
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: true
	//cookie: { secure: true }   /*secure https这样的情况才可以访问cookie*/
}));
app.use(cookieParser());

function checkNoneLogin(originalUrl) {
	if(originalUrl.indexOf('/user/loginIn.do') == 0) {
		return true;
	}else if(originalUrl.indexOf('/user/loginOut.do') == 0) {
		return true;
	}
	return false;
}
app.all('/*.do', (req, res, next) => {
	let userId = (req.cookies && req.cookies.userId) || '';
	console.log(req.cookies);
	if(req.session && req.session.userId && userId) {
		next();
	}else if(checkNoneLogin(req.originalUrl)) {
		next();
	}else {
		res.send({
			status: '416',
			msg: '未登录',
		})
	}
});


app.use(router).use(users).use(orders);
app.use(express.static('./public'));


 
var server = app.listen(3000, function () {//应用启动端口为8081
    var host = server.address().address;
    var port = server.address().port;
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});